package com.yx.cloud.product.sdk.tmall;

import android.content.Context;
import android.util.Log;

import com.aaa.async.DeferredObject;
import com.aaa.async.Promise;
import com.aliyun.aligeniessp_1_0.models.*;
import com.aliyun.alink.business.devicecenter.api.add.DeviceInfo;
import com.aliyun.alink.business.devicecenter.api.discovery.DiscoveryType;
import com.aliyun.alink.business.devicecenter.api.discovery.IDeviceDiscoveryListener;
import com.aliyun.alink.business.devicecenter.api.discovery.LocalDeviceMgr;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import com.iot.common.utils.LogUtils;
import com.yx.cloud.bean.tmall.AuthorizedLogin;
import com.yx.cloud.bean.tmall.TmallUnbindDeviceParam;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.iot.common.utils.Event;
import com.yx.cloud.product.sdk.tmall.req.AddAndRemoveFavoriteContentParam;
import com.yx.cloud.product.sdk.tmall.req.CreateMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.GetListAlbumDetailParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListCateContentParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.SearchContentParam;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AliGenieSdk {
    private static final String TAG = "AliGenieSdk";
    public static int MSG_TMALELF_PALYSTATE = 2000;
    public static int MSG_TMALELF_PALYLIST = 2001;
    public static int MSG_RETURN_SUCCESS_CODE = 200;
    private TmallListener listener;
    private static DeviceStatus currentMusic;
    private static com.aliyun.aligeniessp_1_0.Client client;
    private OnCallBack callBack;

    private AliGenieSdk() {
    }

    //单例
    public static AliGenieSdk get() {
        return InstanceHodler.aliGenieSdk;
    }

    //初始化 天猫精灵sdk
    public static void init() {

        //TODO 初始化SDK
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //初始化设备 或者切换设备
        get().registListener(new TmallListener() {
            @Override
            public void onPlayState(DeviceStatus state) {
                Event.newBuilder().type(MSG_TMALELF_PALYSTATE).content(state).send();
            }

            @Override
            public void onGetPlayerList(List<MusicInfo> musicInfos) {
                Event.newBuilder().type(MSG_TMALELF_PALYLIST).content(musicInfos).send();
            }
        });
    }

    public static com.aliyun.aligeniessp_1_0.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setProtocol("https")
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint("openapi.aligenie.com");// dev-openapi.aligenie.com  openapi.aligenie.com
        return new com.aliyun.aligeniessp_1_0.Client(config);
    }

    /**
     * 根据选品池ID查询选品池内容
     */
    public Promise<List<MusicInfo>, TeaException> getMusicListByTopicId(final GetMusicListParam param) {
        DeferredObject<List<MusicInfo>, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ScgSearchRequest.ScgSearchRequestScgFilterPageParam scgFilterPageParam = new ScgSearchRequest.ScgSearchRequestScgFilterPageParam()
                .setPageSize(param.getPageSize())
                .setPageNum(param.getPageNum());
        ScgSearchRequest.ScgSearchRequestScgFilterSortParam scgFilterSortParam = new ScgSearchRequest.ScgSearchRequestScgFilterSortParam()
                .setSortKey("internal_id")
                .setSortOrder("ASC");
        ScgSearchRequest.ScgSearchRequestScgFilterOffSetParam scgFilterOffSetParam = new ScgSearchRequest.ScgSearchRequestScgFilterOffSetParam()
                .setLimit(param.getPageSize())
                .setOffset(param.getPageNum());
        ScgSearchRequest.ScgSearchRequestScgFilter scgFilter = new ScgSearchRequest.ScgSearchRequestScgFilter()
                .setUseOffSet(true)
                .setOffSetParam(scgFilterOffSetParam)
                .setSortParam(scgFilterSortParam)
                .setPageParam(scgFilterPageParam);
        ScgSearchRequest scgSearchRequest = new ScgSearchRequest()
                .setTopicId(param.getTopicType())
                .setScgFilter(scgFilter);
        ScgSearchResponse scgSearchResponse;
        try {
            scgSearchResponse = client.scgSearch(scgSearchRequest);
            Log.d("music", new Gson().toJson(scgSearchResponse));
            List<MusicInfo> musicInfoList = new ArrayList<>();
            ScgSearchResponseBody body = scgSearchResponse.getBody();
            List<ScgSearchResponseBody.ScgSearchResponseBodyResult> responseBodyResultList = body.getResult();
            for (int i = 0; i < responseBodyResultList.size(); i++) {
                ScgSearchResponseBody.ScgSearchResponseBodyResult result = responseBodyResultList.get(i);
                MusicInfo musicInfo = new MusicInfo();
                musicInfo.setTitle(result.getTitle());
                musicInfo.setSingers(result.getSingers());
                if (result.getCover().getImg() == null) {
                    if (result.getCover().getLarge() == null) {
                        if (result.getCover().getMedium() == null) {
                            musicInfo.setCoverUrl(result.getCover().getSmall());
                        } else {
                            musicInfo.setCoverUrl(result.getCover().getMedium());
                        }
                    } else {
                        musicInfo.setCoverUrl(result.getCover().getLarge());
                    }
                } else {
                    musicInfo.setCoverUrl(result.getCover().getImg());
                }
                musicInfo.setRawId(result.getRawId().toString());
                musicInfo.setAlbumRawId(result.getAlbumRawId());
                musicInfo.setSource(result.getSource());
                musicInfoList.add(musicInfo);
            }
            deferredObject.resolve(musicInfoList);
            Log.d("music", new Gson().toJson(musicInfoList));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(true).extra(param).content(musicInfoList).send();
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(err.code).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(err.code).send();
        }

        return deferredObject.promise();
    }

    public void getMusicListCateInfo() {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ListCateInfoRequest listCateInfoRequest = new ListCateInfoRequest()
                .setType("song");
        try {
            ListCateInfoResponse listCateInfoResponse = client.listCateInfo(listCateInfoRequest);
            Log.d("music", new Gson().toJson(listCateInfoResponse));
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            err.printStackTrace();
            Log.d("music", err.code + "message: " + err.message);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            err.printStackTrace();
            Log.d("music", err.code + "message: " + err.message);
        }
    }

    /**
     * 获取类目下的专辑列表
     */

    public Promise<List<MusicInfo>, TeaException> getMusicListCateContent(GetMusicListCateContentParam param) {
        DeferredObject<List<MusicInfo>, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ListCateContentRequest.ListCateContentRequestDeviceInfo deviceInfo = new ListCateContentRequest.ListCateContentRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        ListCateContentRequest.ListCateContentRequestUserInfo userInfo = new ListCateContentRequest.ListCateContentRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        ListCateContentRequest.ListCateContentRequestRequest request = new ListCateContentRequest.ListCateContentRequestRequest()
                .setCateId(param.getCateId())
                .setSortBy("hot_score")
                .setSortOrder("DESC")
                .setPageNum(param.getPageNum())
                .setPageSize(param.getPageSize())
                .setIsAlbum(param.isAlbum());
        ListCateContentRequest listCateContentRequest = new ListCateContentRequest()
                .setRequest(request)
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            ListCateContentResponse listCateContentResponse = client.listCateContent(listCateContentRequest);
            Log.d("music", new Gson().toJson(listCateContentResponse));
            List<MusicInfo> musicInfoList = new ArrayList<>();
            ListCateContentResponseBody body = listCateContentResponse.getBody();
            if (body.getCode() == MSG_RETURN_SUCCESS_CODE) {
                ListCateContentResponseBody.ListCateContentResponseBodyResult listCateContentResponseBodyResult = body.getResult();
                long totalSize = listCateContentResponseBodyResult.getTotalSize();
                param.setTotalSize(totalSize);
                List<ListCateContentResponseBody.ListCateContentResponseBodyResultOpenDataItemList> listCateContentResponseBodyResultOpenDataItemLists = listCateContentResponseBodyResult.getOpenDataItemList();
                for (int i = 0; i < listCateContentResponseBodyResultOpenDataItemLists.size(); i++) {
                    ListCateContentResponseBody.ListCateContentResponseBodyResultOpenDataItemList listCateContentResponseBodyResultOpenDataItemList = listCateContentResponseBodyResultOpenDataItemLists.get(i);
               /* if(listCateContentResponseBodyResultOpenDataItemList.getValid().equals("NOT_VALID")){
                    continue;
                }*/
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setId(listCateContentResponseBodyResultOpenDataItemList.getId());
                    musicInfo.setTitle(listCateContentResponseBodyResultOpenDataItemList.getTitle());
                    if (listCateContentResponseBodyResultOpenDataItemList.getAuthors() != null && listCateContentResponseBodyResultOpenDataItemList.getAuthors().size() > 0) {
                        musicInfo.setSingers(listCateContentResponseBodyResultOpenDataItemList.getAuthors().get(0).getTitle());
                    } else {
                        musicInfo.setSingers("");
                    }

                    if (listCateContentResponseBodyResultOpenDataItemList.getCover().getImg() == null) {
                        if (listCateContentResponseBodyResultOpenDataItemList.getCover().getLarge() == null) {
                            if (listCateContentResponseBodyResultOpenDataItemList.getCover().getMedium() == null) {
                                musicInfo.setCoverUrl(listCateContentResponseBodyResultOpenDataItemList.getCover().getSmall());
                            } else {
                                musicInfo.setCoverUrl(listCateContentResponseBodyResultOpenDataItemList.getCover().getMedium());
                            }
                        } else {
                            musicInfo.setCoverUrl(listCateContentResponseBodyResultOpenDataItemList.getCover().getLarge());
                        }
                    } else {
                        musicInfo.setCoverUrl(listCateContentResponseBodyResultOpenDataItemList.getCover().getImg());
                    }
                    musicInfo.setRawId(listCateContentResponseBodyResultOpenDataItemList.getRawId());
                    musicInfo.setContentType(listCateContentResponseBodyResultOpenDataItemList.getItemType());
                    musicInfo.setSource(listCateContentResponseBodyResultOpenDataItemList.getSource());
                    musicInfoList.add(musicInfo);
                }
                Log.d("music", "getMusicListCateContent success");
                Log.d("music", new Gson().toJson(musicInfoList));
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(true).extra(param).content(musicInfoList).send();
            } else {
                Log.d("music", "getMusicListCateContent fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(body.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(err.message).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(err.message).send();
        }
        return deferredObject.promise();
    }

    /**
     * 获取每日推荐的音乐或者音频
     */
    public Promise<List<MusicInfo>, TeaException> getListRecommendContent(GetMusicListCateContentParam param) {
        DeferredObject<List<MusicInfo>, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ListRecommendContentRequest.ListRecommendContentRequestDeviceInfo deviceInfo = new ListRecommendContentRequest.ListRecommendContentRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        ListRecommendContentRequest.ListRecommendContentRequestUserInfo userInfo = new ListRecommendContentRequest.ListRecommendContentRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        ListRecommendContentRequest.ListRecommendContentRequestRequest request = new ListRecommendContentRequest.ListRecommendContentRequestRequest()
                .setType("song")
                .setCount(param.getPageSize());
        ListRecommendContentRequest listRecommendContentRequest = new ListRecommendContentRequest()
                .setRequest(request)
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            ListRecommendContentResponse listRecommendContentResponse = client.listRecommendContent(listRecommendContentRequest);
            Log.d("music", new Gson().toJson(listRecommendContentResponse));
            List<MusicInfo> musicInfoList = new ArrayList<>();
            ListRecommendContentResponseBody body = listRecommendContentResponse.getBody();
            if (body.getCode() == MSG_RETURN_SUCCESS_CODE) {
                List<ListRecommendContentResponseBody.ListRecommendContentResponseBodyResult> listRecommendContentResponseBodyResults = body.getResult();
                for (int i = 0; i < listRecommendContentResponseBodyResults.size(); i++) {
                    ListRecommendContentResponseBody.ListRecommendContentResponseBodyResult listRecommendContentResponseBodyResult = listRecommendContentResponseBodyResults.get(i);
               /* if(listCateContentResponseBodyResultOpenDataItemList.getValid().equals("NOT_VALID")){
                    continue;
                }*/
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setTitle(listRecommendContentResponseBodyResult.getTitle());
                    if (listRecommendContentResponseBodyResult.getAuthors() != null && listRecommendContentResponseBodyResult.getAuthors().size() > 0) {
                        musicInfo.setSingers(listRecommendContentResponseBodyResult.getAuthors().get(0).getTitle());
                    } else {
                        musicInfo.setSingers("");
                    }

                    if (listRecommendContentResponseBodyResult.getCover().getImg() == null) {
                        if (listRecommendContentResponseBodyResult.getCover().getLarge() == null) {
                            if (listRecommendContentResponseBodyResult.getCover().getMedium() == null) {
                                musicInfo.setCoverUrl(listRecommendContentResponseBodyResult.getCover().getSmall());
                            } else {
                                musicInfo.setCoverUrl(listRecommendContentResponseBodyResult.getCover().getMedium());
                            }
                        } else {
                            musicInfo.setCoverUrl(listRecommendContentResponseBodyResult.getCover().getLarge());
                        }
                    } else {
                        musicInfo.setCoverUrl(listRecommendContentResponseBodyResult.getCover().getImg());
                    }
                    musicInfo.setRawId(listRecommendContentResponseBodyResult.getRawId());
                    musicInfo.setContentType(listRecommendContentResponseBodyResult.getItemType());
                    musicInfo.setSource(listRecommendContentResponseBodyResult.getSource());
                    musicInfoList.add(musicInfo);
                }
                Log.d("music", "getListRecommendContent success");
                Log.d("music", new Gson().toJson(musicInfoList));
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(true).extra(param).content(musicInfoList).send();
            } else {
                Log.d("music", "getListRecommendContent fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).content(body.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MUSIC_LIST).result(false).extra(param).content(err.getMessage()).send();
        }
        return deferredObject.promise();
    }

    /**
     * 按照特定的id获取专辑信息
     */
    public Promise<MusicInfo, TeaException> getAlbum(long albumId) {
        DeferredObject<MusicInfo, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetAlbumRequest getAlbumRequest = new GetAlbumRequest()
                .setId(albumId)
                .setType("song");
        try {
            GetAlbumResponse getAlbumResponse = client.getAlbum(getAlbumRequest);
            Log.d("music", new Gson().toJson(getAlbumResponse));
            GetAlbumResponseBody getAlbumResponseBody = getAlbumResponse.getBody();
            if (getAlbumResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                GetAlbumResponseBody.GetAlbumResponseBodyResult getAlbumResponseBodyResult = getAlbumResponseBody.getResult();
                MusicInfo musicInfo = new MusicInfo();
                musicInfo.setTitle(getAlbumResponseBodyResult.getTitle());
                if (getAlbumResponseBodyResult.getAuthors() != null && getAlbumResponseBodyResult.getAuthors().size() > 0) {
                    musicInfo.setSingers(getAlbumResponseBodyResult.getAuthors().get(0).getTitle());
                } else {
                    musicInfo.setSingers("");
                }

                if (getAlbumResponseBodyResult.getCover().getImg() == null) {
                    if (getAlbumResponseBodyResult.getCover().getLarge() == null) {
                        if (getAlbumResponseBodyResult.getCover().getMedium() == null) {
                            musicInfo.setCoverUrl(getAlbumResponseBodyResult.getCover().getSmall());
                        } else {
                            musicInfo.setCoverUrl(getAlbumResponseBodyResult.getCover().getMedium());
                        }
                    } else {
                        musicInfo.setCoverUrl(getAlbumResponseBodyResult.getCover().getLarge());
                    }
                } else {
                    musicInfo.setCoverUrl(getAlbumResponseBodyResult.getCover().getImg());
                }
                musicInfo.setRawId(getAlbumResponseBodyResult.getRawId());
                musicInfo.setSource(getAlbumResponseBodyResult.getSource());
                Log.d("music", "getAlbum success");
                Log.d("music", new Gson().toJson(musicInfo));
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_DETAIL).result(true).content(musicInfo).send();
            } else {
                Log.d("music", "getAlbum fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_DETAIL).result(false).content("code is not 200").send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_DETAIL).result(false).content(err.message).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_DETAIL).result(false).content(err.message).send();
        }
        return deferredObject.promise();
    }

    /**
     * 获取音乐音频专辑里面的内容列表
     */
    public Promise<List<MusicInfo>, TeaException> getListAlbumDetail(GetListAlbumDetailParam param) {
        DeferredObject<List<MusicInfo>, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ListAlbumDetailRequest listAlbumDetailRequest = new ListAlbumDetailRequest()
                .setId(param.getId())
                .setPageNum(param.getPageNum())
                .setPageSize(param.getPageSize());
        try {
            ListAlbumDetailResponse listAlbumDetailResponse = client.listAlbumDetail(listAlbumDetailRequest);
            Log.d("music", new Gson().toJson(listAlbumDetailResponse));
            List<MusicInfo> musicInfoList = new ArrayList<>();
            ListAlbumDetailResponseBody body = listAlbumDetailResponse.getBody();
            if (body.getCode() == MSG_RETURN_SUCCESS_CODE) {
                ListAlbumDetailResponseBody.ListAlbumDetailResponseBodyResult listAlbumDetailResponseBodyResult = body.getResult();
                param.setTotalSize(listAlbumDetailResponseBodyResult.getTotalSize());
                List<ListAlbumDetailResponseBody.ListAlbumDetailResponseBodyResultOpenDataItemList> listAlbumDetailResponseBodyResultOpenDataItemLists = listAlbumDetailResponseBodyResult.getOpenDataItemList();
                for (int i = 0; i < listAlbumDetailResponseBodyResultOpenDataItemLists.size(); i++) {
                    ListAlbumDetailResponseBody.ListAlbumDetailResponseBodyResultOpenDataItemList listAlbumDetailResponseBodyResultOpenDataItemList = listAlbumDetailResponseBodyResultOpenDataItemLists.get(i);
               /* if(listCateContentResponseBodyResultOpenDataItemList.getValid().equals("NOT_VALID")){
                    continue;
                }*/
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setTitle(listAlbumDetailResponseBodyResultOpenDataItemList.getTitle());
                    if (listAlbumDetailResponseBodyResultOpenDataItemList.getAuthors() != null && listAlbumDetailResponseBodyResultOpenDataItemList.getAuthors().size() > 0) {
                        musicInfo.setSingers(listAlbumDetailResponseBodyResultOpenDataItemList.getAuthors().get(0).getTitle());
                    } else {
                        musicInfo.setSingers("");
                    }

                    if (listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getImg() == null) {
                        if (listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getLarge() == null) {
                            if (listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getMedium() == null) {
                                musicInfo.setCoverUrl(listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getSmall());
                            } else {
                                musicInfo.setCoverUrl(listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getMedium());
                            }
                        } else {
                            musicInfo.setCoverUrl(listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getLarge());
                        }
                    } else {
                        musicInfo.setCoverUrl(listAlbumDetailResponseBodyResultOpenDataItemList.getCover().getImg());
                    }
                    musicInfo.setRawId(listAlbumDetailResponseBodyResultOpenDataItemList.getRawId());
                    musicInfo.setContentType(listAlbumDetailResponseBodyResultOpenDataItemList.getItemType());
                    musicInfo.setSource(listAlbumDetailResponseBodyResultOpenDataItemList.getSource());
                    musicInfoList.add(musicInfo);
                }
                Log.d("music", "getListAlbumDetail success");
                Log.d("music", new Gson().toJson(musicInfoList));
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_LIST_DETAIL).result(true).extra(param).content(musicInfoList).send();
            } else {
                Log.d("music", "getListAlbumDetail fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_LIST_DETAIL).result(false).extra(param).content(body.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_LIST_DETAIL).result(false).content(err.code).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_LIST_DETAIL).result(false).content(err.code).send();
        }
        return deferredObject.promise();
    }


    /**
     * 创建播放列表并播放指定的内容
     */
    public void createMusicList(List<MusicInfo> musicInfoList, CreateMusicListParam param) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CreatePlayingListRequest.CreatePlayingListRequestUserInfo userInfo = new CreatePlayingListRequest.CreatePlayingListRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        CreatePlayingListRequest.CreatePlayingListRequestDeviceInfo deviceInfo = new CreatePlayingListRequest.CreatePlayingListRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        List<CreatePlayingListRequest.CreatePlayingListRequestOpenCreatePlayingListRequestContentList> contentList = new ArrayList<>();
        for (int i = 0; i < musicInfoList.size(); i++) {
            CreatePlayingListRequest.CreatePlayingListRequestOpenCreatePlayingListRequestContentList openCreatePlayingListRequestContentList = new CreatePlayingListRequest.CreatePlayingListRequestOpenCreatePlayingListRequestContentList()
                    .setSource(musicInfoList.get(i).getSource())
                    .setRawId(musicInfoList.get(i).getRawId());
            contentList.add(openCreatePlayingListRequestContentList);
        }
        CreatePlayingListRequest.CreatePlayingListRequestOpenCreatePlayingListRequest openCreatePlayingListRequest = new CreatePlayingListRequest.CreatePlayingListRequestOpenCreatePlayingListRequest()
                .setPlayFrom("default")
                .setContentType(param.getContentType())
                .setContentList(contentList)
                .setIndex(param.getPlayIndex())
                .setPlayMode(param.getPlayMode());
        CreatePlayingListRequest createPlayingListRequest = new CreatePlayingListRequest()
                .setOpenCreatePlayingListRequest(openCreatePlayingListRequest)
                .setDeviceInfo(deviceInfo)
                .setUserInfo(userInfo);
        try {
            CreatePlayingListResponse createPlayingListResponse = client.createPlayingList(createPlayingListRequest);
            CreatePlayingListResponseBody createPlayingListResponseBody = createPlayingListResponse.getBody();
            if (createPlayingListResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                if (createPlayingListResponseBody.getSuccess().equals("true")) {
                    Log.d("music", "createMusicList success");
                    Log.d("music", new Gson().toJson(createPlayingListRequest));
                    Event.newBuilder().type(Event.MESSAGE_TYPE_CREATE_MUSIC_LIST).result(true).content(musicInfoList).send();
                } else if (createPlayingListResponseBody.getSuccess().equals("false")) {
                    Log.d("music", "createMusicList fail");
                    Event.newBuilder().type(Event.MESSAGE_TYPE_CREATE_MUSIC_LIST).result(false).content(createPlayingListResponseBody.getMessage()).send();
                }
            } else {
                Log.d("music", "createMusicList fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_CREATE_MUSIC_LIST).result(false).content(createPlayingListResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_CREATE_MUSIC_LIST).result(false).content(err.message).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_CREATE_MUSIC_LIST).result(false).content(err.message).send();
        }
    }

    /**
     * 播放暂停控制
     */
    public void playAndPause(String cmd) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        PlayAndPauseControlRequest.PlayAndPauseControlRequestDeviceInfo deviceInfo = new PlayAndPauseControlRequest.PlayAndPauseControlRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        PlayAndPauseControlRequest.PlayAndPauseControlRequestUserInfo userInfo = new PlayAndPauseControlRequest.PlayAndPauseControlRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        PlayAndPauseControlRequest.PlayAndPauseControlRequestOpenPlayAndPauseControlParam openPlayAndPauseControlParam = new PlayAndPauseControlRequest.PlayAndPauseControlRequestOpenPlayAndPauseControlParam()
                .setOpenPlayAndPauseCommand(cmd);
        PlayAndPauseControlRequest playAndPauseControlRequest = new PlayAndPauseControlRequest()
                .setOpenPlayAndPauseControlParam(openPlayAndPauseControlParam)
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            PlayAndPauseControlResponse playAndPauseControlResponse = client.playAndPauseControl(playAndPauseControlRequest);
            Log.d("music", new Gson().toJson(playAndPauseControlResponse));
            PlayAndPauseControlResponseBody playAndPauseControlResponseBody = playAndPauseControlResponse.getBody();
            if (playAndPauseControlResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                boolean result = playAndPauseControlResponseBody.getResult();
                Log.d("music", "playAndPause success");
                Log.d("music", "playAndPause result is ==== " + result);
                Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_AND_PAUSE).result(true).content(result).send();
            } else {
                Log.d("music", "playAndPause fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_AND_PAUSE).result(false).content(playAndPauseControlResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_AND_PAUSE).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_AND_PAUSE).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 播放模式切换
     */
    public void playModeControl(String mode) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        PlayModeControlRequest.PlayModeControlRequestDeviceInfo deviceInfo = new PlayModeControlRequest.PlayModeControlRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        PlayModeControlRequest.PlayModeControlRequestUserInfo userInfo = new PlayModeControlRequest.PlayModeControlRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        PlayModeControlRequest.PlayModeControlRequestOpenPlayModeControlRequest param = new PlayModeControlRequest.PlayModeControlRequestOpenPlayModeControlRequest()
                .setOpenPlayMode(mode);
        PlayModeControlRequest playModeControlRequest = new PlayModeControlRequest()
                .setOpenPlayModeControlRequest(param)
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            PlayModeControlResponse playModeControlResponse = client.playModeControl(playModeControlRequest);
            Log.d("music", new Gson().toJson(playModeControlResponse));
            PlayModeControlResponseBody playModeControlResponseBody = playModeControlResponse.getBody();
            if (playModeControlResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                PlayModeControlResponseBody.PlayModeControlResponseBodyResult result = playModeControlResponseBody.getResult();
                String openPlayMode = result.getOpenPlayMode();
                Log.d("music", "playModeControl success");
                Log.d("music", "playModeControl openPlayMode is ==== " + openPlayMode);
                Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_MODE_CONTROL).result(true).content(openPlayMode).send();
            } else {
                Log.d("music", "playModeControl fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_MODE_CONTROL).result(false).content(playModeControlResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_MODE_CONTROL).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PLAY_MODE_CONTROL).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 设备音量等属性值控制
     */
    public void volumeControl(int volume, Boolean isMuted) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceControlRequest.DeviceControlRequestDeviceInfo deviceInfo = new DeviceControlRequest.DeviceControlRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        DeviceControlRequest.DeviceControlRequestControlRequest controlRequest = new DeviceControlRequest.DeviceControlRequestControlRequest()
                .setVolume(volume)
                .setMuted(isMuted);
        DeviceControlRequest deviceControlRequest = new DeviceControlRequest()
                .setControlRequest(controlRequest)
                .setDeviceInfo(deviceInfo);
        try {
            DeviceControlResponse deviceControlResponse = client.deviceControl(deviceControlRequest);
            Log.d("music", new Gson().toJson(deviceControlResponse));
            DeviceControlResponseBody deviceControlResponseBody = deviceControlResponse.getBody();
            if (deviceControlResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                boolean result = deviceControlResponseBody.getResult();
                Log.d("music", "volumeControl success");
                Log.d("music", "volumeControl result is " + result);
                Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_VOLUME_CONTROL).result(result).content(deviceControlResponseBody.getMessage()).send();
            } else {
                Log.d("music", "volumeControl fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_VOLUME_CONTROL).result(false).content(deviceControlResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_VOLUME_CONTROL).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_VOLUME_CONTROL).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 进度控制
     */
    public void progressControl(int progress) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ProgressControlRequest.ProgressControlRequestOpenProgressControlRequest openProgressControlRequest = new ProgressControlRequest.ProgressControlRequestOpenProgressControlRequest()
                .setProgress(progress);
        ProgressControlRequest.ProgressControlRequestDeviceInfo deviceInfo = new ProgressControlRequest.ProgressControlRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        ProgressControlRequest.ProgressControlRequestUserInfo userInfo = new ProgressControlRequest.ProgressControlRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        ProgressControlRequest progressControlRequest = new ProgressControlRequest()
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo)
                .setOpenProgressControlRequest(openProgressControlRequest);
        try {
            ProgressControlResponse progressControlResponse = client.progressControl(progressControlRequest);
            ProgressControlResponseBody progressControlResponseBody = progressControlResponse.getBody();
            if (progressControlResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                boolean result = progressControlResponseBody.getResult();
                Log.d("music", "progressControl success");
                Log.d("music", "progressControl progress is " + result);
                Event.newBuilder().type(Event.MESSAGE_TYPE_PROGRESS_CONTROL).result(result).content(progressControlResponseBody.getMessage()).send();
            } else {
                Log.d("music", "progressControl fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_PROGRESS_CONTROL).result(false).content(progressControlResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PROGRESS_CONTROL).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PROGRESS_CONTROL).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 播放列表点击播放
     */
    public Promise<MusicInfo, TeaException> indexControlPlay(int index) {
        DeferredObject<MusicInfo, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        IndexControlPlayingListRequest.IndexControlPlayingListRequestOpenIndexControlRequest openIndexControlRequest = new IndexControlPlayingListRequest.IndexControlPlayingListRequestOpenIndexControlRequest()
                .setIndex(index)
                .setNeedContentContinued(true);
        IndexControlPlayingListRequest.IndexControlPlayingListRequestUserInfo userInfo = new IndexControlPlayingListRequest.IndexControlPlayingListRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        IndexControlPlayingListRequest.IndexControlPlayingListRequestDeviceInfo deviceInfo = new IndexControlPlayingListRequest.IndexControlPlayingListRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        IndexControlPlayingListRequest indexControlPlayingListRequest = new IndexControlPlayingListRequest()
                .setDeviceInfo(deviceInfo)
                .setUserInfo(userInfo)
                .setOpenIndexControlRequest(openIndexControlRequest);
        try {
            IndexControlPlayingListResponse indexControlPlayingListResponse = client.indexControlPlayingList(indexControlPlayingListRequest);
            Log.d("music", new Gson().toJson(indexControlPlayingListResponse));
            IndexControlPlayingListResponseBody indexControlPlayingListResponseBody = indexControlPlayingListResponse.getBody();
            if (indexControlPlayingListResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                IndexControlPlayingListResponseBody.IndexControlPlayingListResponseBodyResult indexControlPlayingListResponseBodyResult = indexControlPlayingListResponseBody.getResult();
                MusicInfo musicInfo = new MusicInfo();
                musicInfo.setTitle(indexControlPlayingListResponseBodyResult.getTitle());
                musicInfo.setSingers(indexControlPlayingListResponseBodyResult.getSinger());

                if (indexControlPlayingListResponseBodyResult.getCover() != null) {
                    if (indexControlPlayingListResponseBodyResult.getCover().getImg() == null) {
                        if (indexControlPlayingListResponseBodyResult.getCover().getLarge() == null) {
                            if (indexControlPlayingListResponseBodyResult.getCover().getMedium() == null) {
                                musicInfo.setCoverUrl(indexControlPlayingListResponseBodyResult.getCover().getSmall());
                            } else {
                                musicInfo.setCoverUrl(indexControlPlayingListResponseBodyResult.getCover().getMedium());
                            }
                        } else {
                            musicInfo.setCoverUrl(indexControlPlayingListResponseBodyResult.getCover().getLarge());
                        }
                    } else {
                        musicInfo.setCoverUrl(indexControlPlayingListResponseBodyResult.getCover().getImg());
                    }
                }

                musicInfo.setRawId(indexControlPlayingListResponseBodyResult.getRawId());
                musicInfo.setSource(indexControlPlayingListResponseBodyResult.getSource());
                musicInfo.setProgress(indexControlPlayingListResponseBodyResult.getProgress());
                musicInfo.setAudioLength(indexControlPlayingListResponseBodyResult.getAudioLength());
                musicInfo.setProgress(indexControlPlayingListResponseBodyResult.getPos());
                Log.d("music", "indexControlPlay success");
                Log.d("music", new Gson().toJson(musicInfo));
                Event.newBuilder().type(Event.MESSAGE_TYPE_INDEX_PLAY_MUSIC).result(true).content(musicInfo).send();
            } else {
                Log.d("music", "indexControlPlay fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_INDEX_PLAY_MUSIC).result(false).content(indexControlPlayingListResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_INDEX_PLAY_MUSIC).result(false).content(err.message).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_INDEX_PLAY_MUSIC).result(false).content(err.message).send();
        }
        return deferredObject.promise();
    }

    /**
     * 对创建的播放列表中的内容进行上下一首控制
     */
    public Promise<MusicInfo, TeaException> previousAndNext(String cmd) {
        DeferredObject<MusicInfo, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        PreviousAndNextControlRequest.PreviousAndNextControlRequestDeviceInfo deviceInfo = new PreviousAndNextControlRequest.PreviousAndNextControlRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        PreviousAndNextControlRequest.PreviousAndNextControlRequestUserInfo userInfo = new PreviousAndNextControlRequest.PreviousAndNextControlRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        PreviousAndNextControlRequest.PreviousAndNextControlRequestOpenControlPlayingListRequest openControlPlayingListRequest = new PreviousAndNextControlRequest.PreviousAndNextControlRequestOpenControlPlayingListRequest()
                .setCmd(cmd)
                .setIsFromDevice(false);
        PreviousAndNextControlRequest previousAndNextControlRequest = new PreviousAndNextControlRequest()
                .setOpenControlPlayingListRequest(openControlPlayingListRequest)
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            PreviousAndNextControlResponse previousAndNextControlResponse = client.previousAndNextControl(previousAndNextControlRequest);
            Log.d("music", new Gson().toJson(previousAndNextControlResponse));
            PreviousAndNextControlResponseBody previousAndNextControlResponseBody = previousAndNextControlResponse.getBody();
            if (previousAndNextControlResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                PreviousAndNextControlResponseBody.PreviousAndNextControlResponseBodyResult previousAndNextControlResponseBodyResult = previousAndNextControlResponseBody.getResult();
                MusicInfo musicInfo = new MusicInfo();
                if (previousAndNextControlResponseBodyResult != null) {
                    musicInfo.setTitle(previousAndNextControlResponseBodyResult.getTitle());
                    musicInfo.setSingers(previousAndNextControlResponseBodyResult.getSinger());

                    if (previousAndNextControlResponseBodyResult.getCover() != null) {
                        if (previousAndNextControlResponseBodyResult.getCover().getImg() == null) {
                            if (previousAndNextControlResponseBodyResult.getCover().getLarge() == null) {
                                if (previousAndNextControlResponseBodyResult.getCover().getMedium() == null) {
                                    musicInfo.setCoverUrl(previousAndNextControlResponseBodyResult.getCover().getSmall());
                                } else {
                                    musicInfo.setCoverUrl(previousAndNextControlResponseBodyResult.getCover().getMedium());
                                }
                            } else {
                                musicInfo.setCoverUrl(previousAndNextControlResponseBodyResult.getCover().getLarge());
                            }
                        } else {
                            musicInfo.setCoverUrl(previousAndNextControlResponseBodyResult.getCover().getImg());
                        }
                    }
                    musicInfo.setRawId(previousAndNextControlResponseBodyResult.getRawId());
                    musicInfo.setSource(previousAndNextControlResponseBodyResult.getSource());
                    musicInfo.setProgress(previousAndNextControlResponseBodyResult.getProgress());
                    musicInfo.setAudioLength(previousAndNextControlResponseBodyResult.getAudioLength());
                    musicInfo.setPlayMode(previousAndNextControlResponseBodyResult.getPlayMode());
                    musicInfo.setPos(previousAndNextControlResponseBodyResult.getPos());
                    Log.d("music", "previousAndNext success");
                    Log.d("music", new Gson().toJson(musicInfo));
                    Event.newBuilder().type(Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL).result(true).content(musicInfo).extra(cmd).send();
                } else {
                    Log.d("music", "previousAndNext success but result is null");
                    Event.newBuilder().type(Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL).result(true).content(null).extra(cmd).send();

                }
            } else {
                Log.d("music", "previousAndNext fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL).result(false).content(previousAndNextControlResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL).result(false).content(err.message).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL).result(false).content(err.message).send();
        }
        return deferredObject.promise();
    }

    /**
     * 获取当前播放列表
     */
    public Promise<List<MusicInfo>, TeaException> getPlayingList(GetMusicListParam param) {
        DeferredObject<List<MusicInfo>, TeaException> deferredObject = new DeferredObject<>();
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetCurrentPlayingListRequest.GetCurrentPlayingListRequestOpenQueryPlayListRequest openQueryPlayListRequest = new GetCurrentPlayingListRequest.GetCurrentPlayingListRequestOpenQueryPlayListRequest()
                .setPageNum(param.getPageNum())
                .setPageSize(param.getPageSize());
        GetCurrentPlayingListRequest.GetCurrentPlayingListRequestDeviceInfo deviceInfo = new GetCurrentPlayingListRequest.GetCurrentPlayingListRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        GetCurrentPlayingListRequest.GetCurrentPlayingListRequestUserInfo userInfo = new GetCurrentPlayingListRequest.GetCurrentPlayingListRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        GetCurrentPlayingListRequest getCurrentPlayingListRequest = new GetCurrentPlayingListRequest()
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo)
                .setOpenQueryPlayListRequest(openQueryPlayListRequest);
        try {
            GetCurrentPlayingListResponse getCurrentPlayingListResponse = client.getCurrentPlayingList(getCurrentPlayingListRequest);
            List<MusicInfo> musicInfoList = new ArrayList<>();
            GetCurrentPlayingListResponseBody body = getCurrentPlayingListResponse.getBody();
            if (body.getCode() == MSG_RETURN_SUCCESS_CODE) {
                if (body.getSuccess().equals("true")) {
                    List<GetCurrentPlayingListResponseBody.GetCurrentPlayingListResponseBodyResult> getCurrentPlayingListResponseBodyResults = body.getResult();
                    for (int i = 0; i < getCurrentPlayingListResponseBodyResults.size(); i++) {
                        GetCurrentPlayingListResponseBody.GetCurrentPlayingListResponseBodyResult getCurrentPlayingListResponseBodyResult = getCurrentPlayingListResponseBodyResults.get(i);
                        MusicInfo musicInfo = new MusicInfo();
                        musicInfo.setTitle(getCurrentPlayingListResponseBodyResult.getTitle());
                        musicInfo.setSingers(getCurrentPlayingListResponseBodyResult.getSinger());

                        if (getCurrentPlayingListResponseBodyResult.getCover().getImg() == null) {
                            if (getCurrentPlayingListResponseBodyResult.getCover().getLarge() == null) {
                                if (getCurrentPlayingListResponseBodyResult.getCover().getMedium() == null) {
                                    musicInfo.setCoverUrl(getCurrentPlayingListResponseBodyResult.getCover().getSmall());
                                } else {
                                    musicInfo.setCoverUrl(getCurrentPlayingListResponseBodyResult.getCover().getMedium());
                                }
                            } else {
                                musicInfo.setCoverUrl(getCurrentPlayingListResponseBodyResult.getCover().getLarge());
                            }
                        } else {
                            musicInfo.setCoverUrl(getCurrentPlayingListResponseBodyResult.getCover().getImg());
                        }
                        musicInfo.setRawId(getCurrentPlayingListResponseBodyResult.getRawId());
                        musicInfo.setSource(getCurrentPlayingListResponseBodyResult.getSource());
                        musicInfo.setProgress(getCurrentPlayingListResponseBodyResult.getProgress());
                        musicInfo.setAudioLength(getCurrentPlayingListResponseBodyResult.getAudioLength());
                        musicInfoList.add(musicInfo);
                    }
                    Log.d("music", "getPlayingList success");
                    Log.d("music", new Gson().toJson(musicInfoList));
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST).result(true).extra(param).content(musicInfoList).send();
                } else if (body.getSuccess().equals("false")) {
                    Log.d("music", "getPlayingList fail");
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST).result(false).extra(param).content(body.getMessage()).send();
                }
            } else {
                Log.d("music", "getPlayingList fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST).result(false).extra(param).content(body.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST).result(false).content(err.getMessage()).send();
        }
        return deferredObject.promise();
    }

    /**
     * 获取当前播放项
     */
    public Promise<MusicInfo, TeaException> getPlayingItem() {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeferredObject<MusicInfo, TeaException> deferredObject = new DeferredObject<>();
        GetCurrentPlayingItemRequest.GetCurrentPlayingItemRequestDeviceInfo deviceInfo = new GetCurrentPlayingItemRequest.GetCurrentPlayingItemRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        GetCurrentPlayingItemRequest.GetCurrentPlayingItemRequestUserInfo userInfo = new GetCurrentPlayingItemRequest.GetCurrentPlayingItemRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        GetCurrentPlayingItemRequest getCurrentPlayingItemRequest = new GetCurrentPlayingItemRequest()
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            GetCurrentPlayingItemResponse getCurrentPlayingItemResponse = client.getCurrentPlayingItem(getCurrentPlayingItemRequest);
            GetCurrentPlayingItemResponseBody getCurrentPlayingItemResponseBody = getCurrentPlayingItemResponse.getBody();
            if (getCurrentPlayingItemResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                if (getCurrentPlayingItemResponseBody.getSuccess().equals("true")) {
                    GetCurrentPlayingItemResponseBody.GetCurrentPlayingItemResponseBodyResult getCurrentPlayingItemResponseBodyResult = getCurrentPlayingItemResponseBody.getResult();
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setTitle(getCurrentPlayingItemResponseBodyResult.getTitle());
                    musicInfo.setSingers(getCurrentPlayingItemResponseBodyResult.getSinger());

                    if (getCurrentPlayingItemResponseBodyResult.getCover() != null) {
                        if (getCurrentPlayingItemResponseBodyResult.getCover().getImg() == null) {
                            if (getCurrentPlayingItemResponseBodyResult.getCover().getLarge() == null) {
                                if (getCurrentPlayingItemResponseBodyResult.getCover().getMedium() == null) {
                                    musicInfo.setCoverUrl(getCurrentPlayingItemResponseBodyResult.getCover().getSmall());
                                } else {
                                    musicInfo.setCoverUrl(getCurrentPlayingItemResponseBodyResult.getCover().getMedium());
                                }
                            } else {
                                musicInfo.setCoverUrl(getCurrentPlayingItemResponseBodyResult.getCover().getLarge());
                            }
                        } else {
                            musicInfo.setCoverUrl(getCurrentPlayingItemResponseBodyResult.getCover().getImg());
                        }
                    }

                    musicInfo.setRawId(getCurrentPlayingItemResponseBodyResult.getRawId());
                    musicInfo.setSource(getCurrentPlayingItemResponseBodyResult.getSource());
                    musicInfo.setProgress(getCurrentPlayingItemResponseBodyResult.getProgress());
                    musicInfo.setAudioLength(getCurrentPlayingItemResponseBodyResult.getAudioLength());
                    musicInfo.setPlayMode(getCurrentPlayingItemResponseBodyResult.getPlayMode());
                    musicInfo.setPos(getCurrentPlayingItemResponseBodyResult.getPos());
                    Log.d("music", "getPlayingItem success");
                    Log.d("music", new Gson().toJson(musicInfo));
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_ITEM).result(true).content(musicInfo).send();
                } else if (getCurrentPlayingItemResponseBody.equals("false")) {
                    Log.d("music", "getPlayingItem fail");
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_ITEM).result(false).content(getCurrentPlayingItemResponseBody.getMessage()).send();
                }
            } else {
                Log.d("music", "getPlayingItem fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_ITEM).result(false).content(getCurrentPlayingItemResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_ITEM).result(false).content(err.code).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            deferredObject.reject(new TeaException(err.message, err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_ITEM).result(false).content(err.code).send();
        }
        return deferredObject.promise();
    }

    public void getDeviceStatusInfo() {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        GetDeviceStatusInfoRequest.GetDeviceStatusInfoRequestDeviceInfo deviceInfo = new GetDeviceStatusInfoRequest.GetDeviceStatusInfoRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        GetDeviceStatusInfoRequest getDeviceStatusInfoRequest = new GetDeviceStatusInfoRequest()
                .setDeviceInfo(deviceInfo);
        try {
            GetDeviceStatusInfoResponse getDeviceStatusInfoResponse = client.getDeviceStatusInfo(getDeviceStatusInfoRequest);
            Log.d("music", new Gson().toJson(getDeviceStatusInfoResponse));
            GetDeviceStatusInfoResponseBody getDeviceStatusInfoResponseBody = getDeviceStatusInfoResponse.getBody();
            if (getDeviceStatusInfoResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                GetDeviceStatusInfoResponseBody.GetDeviceStatusInfoResponseBodyResult getDeviceStatusInfoResponseBodyResult = getDeviceStatusInfoResponseBody.getResult();
                int status = getDeviceStatusInfoResponseBodyResult.getOnline();
                Log.d("music", "getDeviceStatusInfo success");
                Log.d("music", "getDeviceStatusInfo device status is " + status);
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS).result(true).content(status).send();
            } else {
                Log.d("music", "getDeviceStatusInfo fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS).result(false).content(getDeviceStatusInfoResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS).result(false).content(err.getMessage()).send();
        }
    }

    public void getDeviceStatusDetail() {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetDeviceStatusDetailRequest.GetDeviceStatusDetailRequestDeviceInfo deviceInfo = new GetDeviceStatusDetailRequest.GetDeviceStatusDetailRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        GetDeviceStatusDetailRequest getDeviceStatusDetailRequest = new GetDeviceStatusDetailRequest()
                .setKeys(java.util.Arrays.asList(
                        "player",
                        "speaker",
                        "power"
                ))
                .setDeviceInfo(deviceInfo);
        try {
            GetDeviceStatusDetailResponse getDeviceStatusDetailResponse = client.getDeviceStatusDetail(getDeviceStatusDetailRequest);
            Log.d("music", new Gson().toJson(getDeviceStatusDetailResponse));
            GetDeviceStatusDetailResponseBody getDeviceStatusDetailResponseBody = getDeviceStatusDetailResponse.getBody();
            if (getDeviceStatusDetailResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                GetDeviceStatusDetailResponseBody.GetDeviceStatusDetailResponseBodyResult result = getDeviceStatusDetailResponseBody.getResult();
                DeviceStatus deviceStatus = new DeviceStatus();
                deviceStatus.setVolume(result.getSpeaker().getVolume());
                deviceStatus.setMuted(result.getSpeaker().getMuted());
                MusicInfo musicInfo = new MusicInfo();
                musicInfo.setMusicPlayStatus(result.getPlayer().getStatus());
                if (musicInfo.getMusicPlayStatus().equals("play")) {
                    long timestamp = Long.valueOf(result.getPlayer().getTimestamp());
                    long currentTimestamp = System.currentTimeMillis();
                    int dValue = (int) (currentTimestamp - timestamp) / 1000;
                    musicInfo.setProgress(Integer.valueOf(result.getPlayer().getProgress()) + dValue);
                } else {
                    musicInfo.setProgress(Integer.valueOf(result.getPlayer().getProgress()));
                }

                if (result.getPlayer().getProgress() == result.getPlayer().getAudioLength()) {
                    musicInfo.setMusicPlayStatus("finish");
                }
                musicInfo.setAudioLength(Integer.valueOf(result.getPlayer().getAudioLength()));
                musicInfo.setTitle(result.getPlayer().getAudioName());
                musicInfo.setSingers(result.getPlayer().getAudioAnchor());
                musicInfo.setSource(result.getPlayer().getSource());
                musicInfo.setRawId(result.getPlayer().getAudioId());
                deviceStatus.setMusicInfo(musicInfo);
                Log.d("music", "getDeviceStatusDetail success");
                Log.d("music", new Gson().toJson(deviceStatus));
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL).result(true).content(deviceStatus).send();
            } else {
                Log.d("music", "getDeviceStatusDetail fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL).result(false).content(getDeviceStatusDetailResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 按照特定的搜索条件搜索
     */
    public void searchContent(SearchContentParam param) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        SearchContentRequest.SearchContentRequestRequest request = new SearchContentRequest.SearchContentRequestRequest()
                .setQuery(param.getQuery())
                .setCate(param.getCate())
                .setSubCate(param.getSubCate())
                .setPageNum(param.getPageNum())
                .setPageSize(param.getPageSize());
        SearchContentRequest.SearchContentRequestDeviceInfo deviceInfo = new SearchContentRequest.SearchContentRequestDeviceInfo()
                .setId(INXNIConstant.DEVICE_ID)
                .setIdType("OPEN_ID")
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE);
        SearchContentRequest.SearchContentRequestUserInfo userInfo = new SearchContentRequest.SearchContentRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setId(INXNIConstant.USER_OPEN_ID)
                .setIdType("OPEN_ID");
        SearchContentRequest searchContentRequest = new SearchContentRequest()
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo)
                .setRequest(request);
        try {
            SearchContentResponse searchContentResponse = client.searchContent(searchContentRequest);
            Log.d("music", new Gson().toJson(searchContentResponse));
            SearchContentResponseBody searchContentResponseBody = searchContentResponse.getBody();
            if (searchContentResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                List<MusicInfo> musicInfoList = new ArrayList<>();
                List<SearchContentResponseBody.SearchContentResponseBodyResult> searchContentResponseBodyResults = searchContentResponseBody.getResult();
                if (searchContentResponseBodyResults != null) {
                    for (int i = 0; i < searchContentResponseBodyResults.size(); i++) {
                        SearchContentResponseBody.SearchContentResponseBodyResult searchContentResponseBodyResult = searchContentResponseBodyResults.get(i);
                        MusicInfo musicInfo = new MusicInfo();
                        musicInfo.setTitle(searchContentResponseBodyResult.getTitle());
                        if (searchContentResponseBodyResult.getAuthors() != null && searchContentResponseBodyResult.getAuthors().size() > 0) {
                            musicInfo.setSingers(searchContentResponseBodyResult.getAuthors().get(0).getTitle());
                        } else {
                            musicInfo.setSingers("");
                        }

                        if (searchContentResponseBodyResult.getCover().getImg() == null) {
                            if (searchContentResponseBodyResult.getCover().getLarge() == null) {
                                if (searchContentResponseBodyResult.getCover().getMedium() == null) {
                                    musicInfo.setCoverUrl(searchContentResponseBodyResult.getCover().getSmall());
                                } else {
                                    musicInfo.setCoverUrl(searchContentResponseBodyResult.getCover().getMedium());
                                }
                            } else {
                                musicInfo.setCoverUrl(searchContentResponseBodyResult.getCover().getLarge());
                            }
                        } else {
                            musicInfo.setCoverUrl(searchContentResponseBodyResult.getCover().getImg());
                        }
                        musicInfo.setId(searchContentResponseBodyResult.getId());
                        musicInfo.setSource(searchContentResponseBodyResult.getSource());
                        musicInfoList.add(musicInfo);
                    }
                    Log.d("music", "SearchContent success");
                    Log.d("music", new Gson().toJson(musicInfoList));
                    Event.newBuilder().type(Event.MESSAGE_TYPE_SEARCH_CONTENT).result(true).extra(param).content(musicInfoList).send();
                } else {
                    Event.newBuilder().type(Event.MESSAGE_TYPE_SEARCH_CONTENT).result(true).extra(param).content(null).send();
                }
            } else {
                Log.d("music", "SearchContent fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_SEARCH_CONTENT).result(false).extra(param).content(searchContentResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_SEARCH_CONTENT).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_SEARCH_CONTENT).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 按照特定的id获取内容信息
     */
    public void getContent(long id) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetContentRequest getContentRequest = new GetContentRequest()
                .setId(id)
                .setType("song");
        try {
            GetContentResponse getContentResponse = client.getContent(getContentRequest);
            GetContentResponseBody getContentResponseBody = getContentResponse.getBody();
            if (getContentResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                GetContentResponseBody.GetContentResponseBodyResult getContentResponseBodyResult = getContentResponseBody.getResult();
                MusicInfo musicInfo = new MusicInfo();
                musicInfo.setTitle(getContentResponseBodyResult.getTitle());
                if (getContentResponseBodyResult.getAuthors() != null && getContentResponseBodyResult.getAuthors().size() > 0) {
                    musicInfo.setSingers(getContentResponseBodyResult.getAuthors().get(0).getTitle());
                } else {
                    musicInfo.setSingers("");
                }

                if (getContentResponseBodyResult.getCover().getImg() == null) {
                    if (getContentResponseBodyResult.getCover().getLarge() == null) {
                        if (getContentResponseBodyResult.getCover().getMedium() == null) {
                            musicInfo.setCoverUrl(getContentResponseBodyResult.getCover().getSmall());
                        } else {
                            musicInfo.setCoverUrl(getContentResponseBodyResult.getCover().getMedium());
                        }
                    } else {
                        musicInfo.setCoverUrl(getContentResponseBodyResult.getCover().getLarge());
                    }
                } else {
                    musicInfo.setCoverUrl(getContentResponseBodyResult.getCover().getImg());
                }
                musicInfo.setRawId(getContentResponseBodyResult.getRawId());
                musicInfo.setContentType(getContentResponseBodyResult.getItemType());
                musicInfo.setSource(getContentResponseBodyResult.getSource());
                Log.d("music", "getContent success");
                Log.d("music", new Gson().toJson(musicInfo));
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CONTENT).result(true).content(musicInfo).send();
            } else {
                Log.d("music", "getContent fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CONTENT).result(false).content(getContentResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CONTENT).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CONTENT).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 收藏或取消收藏
     */
    public void AddAndRemoveFavoriteContent(AddAndRemoveFavoriteContentParam param) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestDeviceInfo deviceInfo = new AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestUserInfo userInfo = new AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestUserInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setId(INXNIConstant.USER_OPEN_ID)
                .setIdType("OPEN_ID");
        AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestOpenAddAndRemoveFavoriteContentRequestOpenSourceRawIdPair openAddAndRemoveFavoriteContentRequestOpenSourceRawIdPair = new AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestOpenAddAndRemoveFavoriteContentRequestOpenSourceRawIdPair()
                .setRawId(param.getRawId())
                .setSource(param.getSource());
        AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestOpenAddAndRemoveFavoriteContentRequest openAddAndRemoveFavoriteContentRequest = new AddAndRemoveFavoriteContentRequest.AddAndRemoveFavoriteContentRequestOpenAddAndRemoveFavoriteContentRequest()
                .setPackageType(param.getType())
                .setOpenSourceRawIdPair(openAddAndRemoveFavoriteContentRequestOpenSourceRawIdPair)
                .setFavoriteCmd(param.getCmd());
        AddAndRemoveFavoriteContentRequest addAndRemoveFavoriteContentRequest = new AddAndRemoveFavoriteContentRequest()
                .setOpenAddAndRemoveFavoriteContentRequest(openAddAndRemoveFavoriteContentRequest)
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo);
        try {
            AddAndRemoveFavoriteContentResponse addAndRemoveFavoriteContentResponse = client.addAndRemoveFavoriteContent(addAndRemoveFavoriteContentRequest);
            Log.d("music", new Gson().toJson(addAndRemoveFavoriteContentResponse));
            AddAndRemoveFavoriteContentResponseBody body = addAndRemoveFavoriteContentResponse.getBody();
            if (body.getCode() == MSG_RETURN_SUCCESS_CODE) {
                boolean result = body.getResult();
                Log.d("music", "AddAndRemoveFavoriteContent success");
                Log.d("music", "AddAndRemoveFavoriteContent result is ==== " + result);
                Event.newBuilder().type(Event.MESSAGE_TYPE_ADD_AND_REMOVE_FAVORITE_CONTENT).result(true).content(result).send();
            } else {
                Log.d("music", "AddAndRemoveFavoriteContent fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_ADD_AND_REMOVE_FAVORITE_CONTENT).result(false).content(body.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_ADD_AND_REMOVE_FAVORITE_CONTENT).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_ADD_AND_REMOVE_FAVORITE_CONTENT).result(false).content(err.getMessage()).send();
        }
    }

    /**
     * 获取历史播放接口
     */
    public void listPlayHistory(GetMusicListParam param) {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ListPlayHistoryRequest.ListPlayHistoryRequestRequest request = new ListPlayHistoryRequest.ListPlayHistoryRequestRequest()
                .setType(param.getType())
                .setPageNum(param.getPageNum())
                .setPageSize(param.getPageSize());
        ListPlayHistoryRequest.ListPlayHistoryRequestDeviceInfo deviceInfo = new ListPlayHistoryRequest.ListPlayHistoryRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.DEVICE_ID);
        ListPlayHistoryRequest.ListPlayHistoryRequestUserInfo userInfo = new ListPlayHistoryRequest.ListPlayHistoryRequestUserInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setId(INXNIConstant.USER_OPEN_ID)
                .setIdType("OPEN_ID");
        ListPlayHistoryRequest listPlayHistoryRequest = new ListPlayHistoryRequest()
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo)
                .setRequest(request);
        try {
            ListPlayHistoryResponse listPlayHistoryResponse = client.listPlayHistory(listPlayHistoryRequest);
            Log.d("music", new Gson().toJson(listPlayHistoryResponse));
            List<MusicInfo> musicInfoList = new ArrayList<>();
            ListPlayHistoryResponseBody listPlayHistoryResponseBody = listPlayHistoryResponse.getBody();
            if (listPlayHistoryResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                List<ListPlayHistoryResponseBody.ListPlayHistoryResponseBodyResult> listPlayHistoryResponseBodyResults = listPlayHistoryResponseBody.getResult();
                for (int i = 0; i < listPlayHistoryResponseBodyResults.size(); i++) {
                    ListPlayHistoryResponseBody.ListPlayHistoryResponseBodyResult listPlayHistoryResponseBodyResult = listPlayHistoryResponseBodyResults.get(i);
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setTitle(listPlayHistoryResponseBodyResult.getTitle());
                    if (listPlayHistoryResponseBodyResult.getAuthors() != null && listPlayHistoryResponseBodyResult.getAuthors().size() > 0) {
                        musicInfo.setSingers(listPlayHistoryResponseBodyResult.getAuthors().get(0).getTitle());
                    } else {
                        musicInfo.setSingers("");
                    }

                    if (listPlayHistoryResponseBodyResult.getCover().getImg() == null) {
                        if (listPlayHistoryResponseBodyResult.getCover().getLarge() == null) {
                            if (listPlayHistoryResponseBodyResult.getCover().getMedium() == null) {
                                musicInfo.setCoverUrl(listPlayHistoryResponseBodyResult.getCover().getSmall());
                            } else {
                                musicInfo.setCoverUrl(listPlayHistoryResponseBodyResult.getCover().getMedium());
                            }
                        } else {
                            musicInfo.setCoverUrl(listPlayHistoryResponseBodyResult.getCover().getLarge());
                        }
                    } else {
                        musicInfo.setCoverUrl(listPlayHistoryResponseBodyResult.getCover().getImg());
                    }
                    musicInfo.setId(listPlayHistoryResponseBodyResult.getId());
                    musicInfo.setContentType(listPlayHistoryResponseBodyResult.getItemType());
                    musicInfo.setSource(listPlayHistoryResponseBodyResult.getSource());
                    musicInfoList.add(musicInfo);
                }
                Log.d("music", "listPlayHistory success");
                Log.d("music", new Gson().toJson(musicInfoList));
                Event.newBuilder().type(Event.MESSAGE_TYPE_LIST_PLAY_HISTORY).result(true).extra(param).content(musicInfoList).send();
            } else {
                Log.d("music", "listPlayHistory fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_LIST_PLAY_HISTORY).result(false).extra(param).content(listPlayHistoryResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_LIST_PLAY_HISTORY).result(false).extra(param).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_LIST_PLAY_HISTORY).result(false).extra(param).content(err.getMessage()).send();
        }
    }

    public void getWeather() {
        try {
            if (client == null) {
                client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetWeatherRequest.GetWeatherRequestDeviceInfo deviceInfo = new GetWeatherRequest.GetWeatherRequestDeviceInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setId(INXNIConstant.DEVICE_ID)
                .setIdType("OPEN_ID");
        GetWeatherRequest.GetWeatherRequestUserInfo userInfo = new GetWeatherRequest.GetWeatherRequestUserInfo()
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setId(INXNIConstant.USER_OPEN_ID)
                .setIdType("OPEN_ID");
        GetWeatherRequest getWeatherRequest = new GetWeatherRequest()
                .setUserInfo(userInfo)
                .setDeviceInfo(deviceInfo)
                .setPayload(new GetWeatherRequest.GetWeatherRequestPayload());
        try {
            GetWeatherResponse response = client.getWeather(getWeatherRequest);
            GetWeatherResponseBody getWeatherResponseBody = response.getBody();
            Log.d("music", new Gson().toJson(response));
            if (getWeatherResponseBody.getCode() == MSG_RETURN_SUCCESS_CODE) {
                Log.d("music", "getWeather success");
                GetWeatherResponseBody.GetWeatherResponseBodyResult getWeatherResponseBodyResult = getWeatherResponseBody.getResult();
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_WEATHER).result(false).content(getWeatherResponseBodyResult.getCurrentMeteorology()).send();
            } else {
                Log.d("music", "getWeather fail");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_WEATHER).result(false).content(getWeatherResponseBody.getMessage()).send();
            }
        } catch (TeaException err) {
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_WEATHER).result(false).content(err.getMessage()).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            Log.d("music", new Gson().toJson(err));
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_WEATHER).result(false).content(err.getMessage()).send();
        }
    }

    public static void destory() {
        get().unregistListener();
    }

    public void registListener(TmallListener listener) {
        this.listener = listener;
    }

    public void unregistListener() {
        this.listener = null;
    }

    private static class InstanceHodler {
        private static AliGenieSdk aliGenieSdk = new AliGenieSdk();
    }

    /**
     * 蓝牙扫描
     */
    public static void tmallBluetoothScan(Context context) {
        Log.d(TAG, "AliGenieSdk Bluetooth scan  :::::::::::::::::::::::::: ");
        // 开始发现设备
        EnumSet<DiscoveryType> discoveryTypes = EnumSet.of(DiscoveryType.GENIE_SOUND_BOX);
        LocalDeviceMgr.getInstance().startDiscovery(context, discoveryTypes, null, new IDeviceDiscoveryListener() {
            @Override
            public void onDeviceFound(DiscoveryType discoveryType, List<DeviceInfo> list) {
                Log.d(TAG, "AliGenieSdk Bluetooth scan  ::::::::::::::::::::::::::onDeviceFound： ");
                if (discoveryType != DiscoveryType.GENIE_SOUND_BOX) {
                    return;
                }
                if (list == null || list.isEmpty()) {
                    return;
                }
                //处理流程
                Log.d(TAG, "AliGenieSdk Bluetooth scan  :::::::::::::::::::::::::: " + list.toString());
                Event.newBuilder().type(Event.MESSAGE_TYPE_TMALL_BLUETOOTH_SCAN).content(list).send();
            }
        });
    }

    /**
     * 获取设备状态：是否在线
     */
    public static void getDeviceStatusInfo(String user_device_id) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetDeviceStatusInfoRequest.GetDeviceStatusInfoRequestDeviceInfo requestDeviceInfo = new GetDeviceStatusInfoRequest.GetDeviceStatusInfoRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(user_device_id);
        GetDeviceStatusInfoRequest deviceStatus = new GetDeviceStatusInfoRequest()
                .setDeviceInfo(requestDeviceInfo);
        try {
            GetDeviceStatusInfoResponse statusInfo = client.getDeviceStatusInfo(deviceStatus);
            GetDeviceStatusInfoResponseBody body = statusInfo.getBody();
            // Log.d(TAG, "--------------------------------AliGenieSdk 设备是否在线" + new Gson().toJson(body));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * AccessToken不存在或已过期时调用
     */
    public static void authorizedLogin(AuthorizedLogin alogin) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        AuthLoginWithThirdUserInfoRequest authorizedLogin = new AuthLoginWithThirdUserInfoRequest()
                .setSceneCode(alogin.getSceneCode())
                .setThirdUserType(alogin.getThirdUserType())
                .setThirdUserIdentifier(alogin.getThirdUserIdentifier());
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getSceneCode()  " + alogin.getSceneCode());
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getSceneCode()  " + alogin.getThirdUserType());
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getSceneCode()  " + alogin.getThirdUserIdentifier());
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getAuthSource()  " + alogin.getAuthSource());
        try {
            AuthLoginWithThirdUserInfoResponse auth_login = client.authLoginWithThirdUserInfo(authorizedLogin);
            AuthLoginWithThirdUserInfoResponseBody body = auth_login.getBody();
            Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN).result(true).content(body).extra(alogin.getAuthSource()).send();
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN).result(false).send();
        }

    }

    /**
     * accessToken鉴权
     */
    public static void accessTokenAuthentication(AuthorizedLogin alogin) {
        Log.d(TAG, "--------------------------------AliGenieSdk accessToken鉴权 ");
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EcologyOpennessAuthenticateRequest authentication = new EcologyOpennessAuthenticateRequest()
                .setLoginStateAccessToken(alogin.getAccessToken())
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setEncodeType(INXNIConstant.ENCODETYPE);
//        Log.d(TAG, "--------------------------------AliGenieSdk accessToken鉴权  accessToken " + alogin.getAccessToken());
//        Log.d(TAG, "--------------------------------AliGenieSdk accessToken鉴权  encodeKey " + INXNIConstant.ENCODEKEY);
//        Log.d(TAG, "--------------------------------AliGenieSdk accessToken鉴权  encodeType " + INXNIConstant.ENCODETYPE);
//        Log.d(TAG, "--------------------------------AliGenieSdk accessToken鉴权  getAuthSource " + alogin.getAuthSource());
        try {
            EcologyOpennessAuthenticateResponse authenticate = client.ecologyOpennessAuthenticate(authentication);
            EcologyOpennessAuthenticateResponseBody body = authenticate.getBody();
            Event.newBuilder().type(Event.MESSAGE_TYPE_ACCESS_TOKEN_AUTHENTIATION).result(true).content(body).extra(alogin.getAuthSource()).send();
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "--------------------------------AliGenieSdk accessToken鉴权  连接超时 " + e.getMessage());
            Event.newBuilder().type(Event.MESSAGE_TYPE_ACCESS_TOKEN_AUTHENTIATION).result(false).extra(alogin.getAuthSource()).send();
        }


    }

    /**
     * 获取设备ID
     */
    public static void getDeviceId(String mac) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Log.d(TAG, "--------------------------------AliGenieSdk 获取天猫设备id mac：" + mac);
//        Log.d(TAG, "--------------------------------AliGenieSdk 获取天猫设备id INXNIConstant.ENCODETYPE：" + INXNIConstant.ENCODETYPE);
//        Log.d(TAG, "--------------------------------AliGenieSdk 获取天猫设备id INXNIConstant.ENCODEKEY：" + INXNIConstant.ENCODEKEY);

        GetDeviceIdByIdentityRequest getDeviceIdByIdentityRequest = new GetDeviceIdByIdentityRequest()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdentityId(mac)//应该从蓝牙中获取
                .setIdentityType("MAC")
                .setProductKey(INXNIConstant.PRODUCT_KEY);//应该从蓝牙中获取
        try {
            GetDeviceIdByIdentityResponse deviceIdByIdentity = client.getDeviceIdByIdentity(getDeviceIdByIdentityRequest);
            GetDeviceIdByIdentityResponseBody body = deviceIdByIdentity.getBody();
            Log.d(TAG, "--------------------------------AliGenieSdk 获取设备id body：" + body);
            Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_ID).result(true).content(body).send();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_ID).result(false).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_ID).result(false).send();
        }
    }

    /**
     * 用户手机号授权登录获取验证码
     */
    public static void userPhoneNumberAuthorizedLoginVerificationCode(AuthorizedLogin aLogin) {
        EcologyOpennessSendVerificationCodeResponse codeResponse;
        EcologyOpennessSendVerificationCodeResponseBody body;
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EcologyOpennessSendVerificationCodeRequest verificationCode = new EcologyOpennessSendVerificationCodeRequest()
                .setPhoneNumber(aLogin.getPhoneNumber())
                .setSessionId(aLogin.getSessionId())
                .setRegion("+86");
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getPhoneNumber()  " + aLogin.getPhoneNumber());
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getSessionId()  " + aLogin.getSessionId());
        Log.d(TAG, "--------------------------------AliGenieSdk alogin.getRegion()  " + aLogin.getRegion());
        try {
            codeResponse = client.ecologyOpennessSendVerificationCode(verificationCode);
            body = codeResponse.getBody();
            Integer code = body.getCode();
            if (code == 200) {
                Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_VERIFICATION_CODE).result(true).content(body).send();
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_VERIFICATION_CODE).result(false).content(code + " : " + body.getMessage()).send();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_VERIFICATION_CODE).result(false).content("error 0 : ").send();
        }

    }

    /**
     * 获取授权登录的用户列表
     */
    public static void getAuthorizedLoginsList(AuthorizedLogin alogin) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FindUserlistToAuthLoginWithPhoneNumberRequest loginList = new FindUserlistToAuthLoginWithPhoneNumberRequest()
                .setSessionId(alogin.getSessionId())
                .setRegion("+86")
                .setPhoneNumber(alogin.getPhoneNumber())
                .setCode(alogin.getVerificationCode());
        try {
            FindUserlistToAuthLoginWithPhoneNumberResponse userlist = client.findUserlistToAuthLoginWithPhoneNumber(loginList);
            FindUserlistToAuthLoginWithPhoneNumberResponseBody body = userlist.getBody();
            //Log.d(TAG, "--------------------------------AliGenieSdk 获取用户授权列表  " + new Gson().toJson(userlist));
            Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_USER_LIST).result(true).content(body).send();
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_AUTHORIZED_LOGIN_USER_LIST).result(false).send();
        }
    }

    /**
     * 通过手机号生成精灵账号进行登录
     */
    public static void phoneNumberAuthorizedLogin(String sessionId) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberRequest phoneNumber = new AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberRequest()
                .setSessionId(sessionId);
        try {
            AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponse byPhoneNumber = client.authLoginWithAligenieUserInfoGeneratedByPhoneNumber(phoneNumber);
            AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponseBody body = byPhoneNumber.getBody();
            Integer code = body.getCode();
            Boolean success = body.getSuccess();
            AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponseBody.AuthLoginWithAligenieUserInfoGeneratedByPhoneNumberResponseBodyResult result = body.getResult();
            if (code == 200 && success && result.toString() != "") {
                Event.newBuilder().type(Event.MESSAGE_TYPE_PHONE_NUMBER_AUTHORIZED_LOGIN).result(true).content(body).send();
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_PHONE_NUMBER_AUTHORIZED_LOGIN).result(false).content("error 1 :" + code + " : " + success).send();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_PHONE_NUMBER_AUTHORIZED_LOGIN).result(false).send();
        }
    }

    /**
     * 解绑设备
     */
    public static void unbindDevice(TmallUnbindDeviceParam param) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        com.aliyun.aligeniessp_1_0.models.UnbindDeviceRequest.UnbindDeviceRequestUserInfo userInfo = new com.aliyun.aligeniessp_1_0.models.UnbindDeviceRequest.UnbindDeviceRequestUserInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(param.getUserOpenId());//用户openID
        com.aliyun.aligeniessp_1_0.models.UnbindDeviceRequest.UnbindDeviceRequestDeviceInfo deviceInfo = new com.aliyun.aligeniessp_1_0.models.UnbindDeviceRequest.UnbindDeviceRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(param.getDeviceId());//设备id
        com.aliyun.aligeniessp_1_0.models.UnbindDeviceRequest unbindDeviceRequest = new com.aliyun.aligeniessp_1_0.models.UnbindDeviceRequest()
                .setDeviceInfo(deviceInfo)
                .setUserInfo(userInfo);
        try {
            UnbindDeviceResponse unbindDevice = client.unbindDevice(unbindDeviceRequest);
            UnbindDeviceResponseBody body = unbindDevice.getBody();
            Integer code = body.getCode();
            String message = body.getMessage();
//            Log.d(TAG, "--------------------------------AliGenieSdk 解绑设备 返回数据 ："+new Gson().toJson(body));
            if (code == 200 && message.equals("success")) {
                //设备是否解绑成功
//                Log.d(TAG, "--------------------------------AliGenieSdk 解绑设备  1111" );
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_DEVICE).result(true).send();
            } else {
//                Log.d(TAG, "--------------------------------AliGenieSdk 解绑设备  333333" );
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_DEVICE).result(false).content("Interface call failed").send();
            }
            // Log.d(TAG, "--------------------------------AliGenieSdk 解绑设备  " + new Gson().toJson(body));
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                Log.d(TAG, "--------------------------------AliGenieSdk 解绑设备  444444" );
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_DEVICE).result(false).content(err.code + " , " + err.message).send();
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                Log.d(TAG, "--------------------------------AliGenieSdk 解绑设备  55555555" );
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_DEVICE).result(false).content(err.code + " , " + err.message).send();
            }
        }
    }


    /**
     * 通过指定的淘宝账号进行授权登录
     */
    public static void taoBaoAuthLogin(String sessionId, String userIdentifier) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "--------------------------------AliGenieSdk 淘宝账号 授权登录 sessionId： " + sessionId);
        Log.d(TAG, "--------------------------------AliGenieSdk 淘宝账号 授权登录 userIdentifier： " + userIdentifier);
        AuthLoginWithTaobaoUserInfoRequest taobaoLogin = new AuthLoginWithTaobaoUserInfoRequest()
                .setSessionId(sessionId)
                .setEncryptedTaobaoUserIdentifier(userIdentifier);
        try {
            AuthLoginWithTaobaoUserInfoResponse taobaoUserInfo = client.authLoginWithTaobaoUserInfo(taobaoLogin);
            AuthLoginWithTaobaoUserInfoResponseBody body = taobaoUserInfo.getBody();
            Integer code = body.getCode();
            String message = body.getMessage();
            // Log.d(TAG, "--------------------------------AliGenieSdk 淘宝账号 授权登录 结果 ： " + new Gson().toJson(body));
            if (200 == code && "OK".equals(message)) {
                Event.newBuilder().type(Event.MESSAGE_TYPE_TAOBAO_AUTH_LOGIN).result(true).content(body).send();
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_TAOBAO_AUTH_LOGIN).result(false).content(message + " : " + code).send();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_TAOBAO_AUTH_LOGIN).result(false).content(e.getMessage()).send();
        }

    }

    /**
     * 通过指定的精灵账号进行授权登录
     */
    public static void tmallGenieTypeLogin(String sessionId, String userIdentifier) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }

        AuthLoginWithAligenieUserInfoRequest tmallGenie = new AuthLoginWithAligenieUserInfoRequest()
                .setSessionId(sessionId)
                .setEncryptedAligenieUserIdentifier(userIdentifier);
        Log.d(TAG, "--------------------------------AliGenieSdk 精灵账号 授权登录 sessionId： " + sessionId);
        Log.d(TAG, "--------------------------------AliGenieSdk 精灵账号 授权登录 userIdentifier： " + userIdentifier);
        try {
            AuthLoginWithAligenieUserInfoResponse genieLogin = client.authLoginWithAligenieUserInfo(tmallGenie);
            AuthLoginWithAligenieUserInfoResponseBody body = genieLogin.getBody();
            Integer code = body.getCode();
            String message = body.getMessage();
            // Log.d(TAG, "--------------------------------AliGenieSdk 精灵账号 授权登录 结果 ： " + new Gson().toJson(body));
            if (200 == code && "OK".equals(message)) {
                Event.newBuilder().type(Event.MESSAGE_TYPE_GENIE_AUTH_LOGIN).result(true).content(body).send();
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_GENIE_AUTH_LOGIN).result(false).content(message + " : " + code).send();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_GENIE_AUTH_LOGIN).result(false).content(e.getMessage()).send();
        }
    }

    /**
     * 获取三方绑定的精灵账号信息
     */
    public static void getAligenieUserInfo(AuthorizedLogin alogin) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.i("getAligenieUserInfo  INXNIConstant.ACCESS_TOKEN : " + INXNIConstant.ACCESS_TOKEN);
        GetAligenieUserInfoRequest request = new GetAligenieUserInfoRequest()
                .setLoginStateAccessToken(alogin.getAccessToken());
        try {
            GetAligenieUserInfoResponse userInfo = client.getAligenieUserInfo(request);
            GetAligenieUserInfoResponseBody body = userInfo.getBody();
            LogUtils.i(" getAligenieUserInfo   body : " + new Gson().toJson(body));
            Integer code = body.getCode();
            String message = body.getMessage();
            if (MSG_RETURN_SUCCESS_CODE == code) {
                String nickname = body.getResult().getAligenieNickname();
                INXNIConstant.TMALL_USER_NICK_NAME = nickname;
                //SharedPrefsUtil.putValue(context, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", nickname);
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALIGENIE_USER_INFO).result(true).content(nickname).extra(alogin.getAuthSource()).send();
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALIGENIE_USER_INFO).result(false).content("error:" + code + "," + message).send();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.i(" getAligenieUserInfo   Exception : " + e.getMessage());
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALIGENIE_USER_INFO).result(false).content("error AligenieUserInfo :" + e.getMessage()).send();
        }

    }

    /**
     * 天猫配网成功后，通过该接口获取扫地机信息后进行配网使用
     */
    public static void getRobotInformation(String user_device_id) {
        List<String> list = new ArrayList<>();
        list.add("customSetting");
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetDeviceSettingRequest.GetDeviceSettingRequestDeviceInfo deviceInfo = new GetDeviceSettingRequest.GetDeviceSettingRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.THIRUSER_IDENTIFIER)
                .setIdType("OPEN_ID")
                //67ccsz6Kn8/kpfbqYesclFlGMxDr9n0DlMPAw2PPsqRjrsQqWz97smpM4RdIBVOEWqtANZ3GF2Zfl/L4SIU0ZBLxypcmeqN4OG9u7e0OoL8=
                .setId(INXNIConstant.DEVICE_ID);//INXNIConstant.DEVICE_ID
        GetDeviceSettingRequest getDeviceSettingRequest = new GetDeviceSettingRequest()
                .setKeys(list)
                .setDeviceInfo(deviceInfo);
        Log.d(TAG, "-----AliGenieSdk getRobotInformation   ENCODETYPE" + INXNIConstant.ENCODETYPE);
        Log.d(TAG, "-----AliGenieSdk getRobotInformation   THIRUSER_IDENTIFIER" + INXNIConstant.THIRUSER_IDENTIFIER);
        Log.d(TAG, "-----AliGenieSdk getRobotInformation   DEVICE_ID : " + INXNIConstant.DEVICE_ID);
        try {
            GetDeviceSettingResponse deviceSetting = client.getDeviceSetting(getDeviceSettingRequest);
            GetDeviceSettingResponseBody body = deviceSetting.getBody();

            Integer code = body.getCode();
            String message = body.getMessage();
            if (code == 200 && "success".equals(message)) {
                Map<String, ?> result = body.getResult();
                if (!result.isEmpty()) {
                    // Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  " + new Gson().toJson(body));
                    String toJson = new Gson().toJson(result);
                    // Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  result " + new Gson().toJson(result));
                    JSONObject jsonObject = new JSONObject(toJson);
                    String customSetting = jsonObject.getString("customSetting");
                    Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  customSetting " + customSetting);
                    if (!customSetting.isEmpty() && customSetting.length() > 0 &&
                            customSetting.contains("BluetoothMac") && customSetting.contains("ty_pid")
                            && customSetting.contains("ty_uuid") && customSetting.contains("WifiMac")) {

                        Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ROBOT_INFO).result(true).content(customSetting).send();
                    } else {
                        Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ROBOT_INFO).result(false).content("customSetting info Is empty").send();
                    }
//                    String substring1 = btMac.substring(0, 17);
//                    String substring2 = btMac.substring(18, 34);
//                    String substring3 = btMac.substring(35, 50);
//                    String substring4 = btMac.substring(51, btMac.length());
//                    Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  substring1 " + substring1);
//                    Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  substring2 " + substring2);
//                    Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  substring3 " + substring3);
//                    Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息  substring4 " + substring4);
                } else {
                    Log.d(TAG, "-----AliGenieSdk 通过该接口获取扫地机信息   数据为空  ");
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ROBOT_INFO).result(false).content("robot info Is empty").send();
                }
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ROBOT_INFO).result(false).content("error network anomaly ").send();
            }
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ROBOT_INFO).result(false).content("error 3 " + err.code + ":" + err.message).send();
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ROBOT_INFO).result(false).content("error 4 " + err.code + ":" + err.message).send();
        }
    }


    public static void getAuthCode() {
        Log.d(TAG, "--------------------------------AliGenieSdk sendRequestWithOkHttp  ");
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetCodeEnhanceRequest.GetCodeEnhanceRequestUserInfo userInfo = new GetCodeEnhanceRequest.GetCodeEnhanceRequestUserInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        GetCodeEnhanceRequest.GetCodeEnhanceRequestChannelInfo channelInfo = new GetCodeEnhanceRequest.GetCodeEnhanceRequestChannelInfo()
                .setChannel("WeChat");
        GetCodeEnhanceRequest getCodeEnhanceRequest = new GetCodeEnhanceRequest()
                .setChannelInfo(channelInfo)
                .setUserInfo(userInfo);
        try {
            GetCodeEnhanceResponse codeEnhance = client.getCodeEnhance(getCodeEnhanceRequest);
            String message = codeEnhance.getBody().message;
            Integer code = codeEnhance.getBody().code;
            if (message.equals("success") && code == 200) {
                String result = codeEnhance.getBody().result;
                INXNIConstant.ALI_GENIE_AUTH_CODE = result;
//                Log.d(TAG, "--------------------------------AliGenieSdk result : " + result);
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_AUTHCODE).result(true).send();
            } else {
                Log.d(TAG, "--------------------------------AliGenieSdk get result 失败了 ");
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_AUTHCODE).result(false).content("getAuthCode Error:" + code + ":" + message).send();
            }

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                Log.d(TAG, "------------------11--------------AliGenieSdk TeaException : ");
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_AUTHCODE).result(false).content("getAuthCode e:" + err.code + ":" + err.message).send();
            Log.d(TAG, "------------------33--------------AliGenieSdk TeaException : " + err.code + " : " + err.message);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                Log.d(TAG, "------------------222--------------AliGenieSdk TeaException : ");
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_AUTHCODE).result(false).content("getAuthCode e:" + err.code + ":" + err.message).send();
            Log.d(TAG, "------------------44--------------AliGenieSdk TeaException err.code:" + err.code + "  err.message:" + err.message);
        }
    }

    /**
     * 获取用户绑定的设备列表（列表中是userDeviceid）
     */
    public static void getUserBindDeviceList() {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        com.aliyun.aligeniessp_1_0.models.ListDeviceByUserIdRequest.ListDeviceByUserIdRequestUserInfo userInfo = new com.aliyun.aligeniessp_1_0.models.ListDeviceByUserIdRequest.ListDeviceByUserIdRequestUserInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(INXNIConstant.USER_OPEN_ID);
        LogUtils.i("getUserBindDeviceList INXNIConstant.ENCODETYPE :" + INXNIConstant.ENCODETYPE);
        LogUtils.i("getUserBindDeviceList INXNIConstant.ENCODEKEY :" + INXNIConstant.ENCODEKEY);
        LogUtils.i("getUserBindDeviceList INXNIConstant.USER_OPEN_ID :" + INXNIConstant.USER_OPEN_ID);
        com.aliyun.aligeniessp_1_0.models.ListDeviceByUserIdRequest listDeviceByUserIdRequest = new com.aliyun.aligeniessp_1_0.models.ListDeviceByUserIdRequest()
                .setUserInfo(userInfo);
        try {
            ListDeviceByUserIdResponse byUserId = client.listDeviceByUserId(listDeviceByUserIdRequest);
            ListDeviceByUserIdResponseBody body = byUserId.getBody();
            Integer code = body.getCode();
            String message = body.getMessage();
            if (code == 200 && "success".equals(message)) {
                List<ListDeviceByUserIdResponseBody.ListDeviceByUserIdResponseBodyResult> result = body.getResult();
                // Log.d(TAG, "AliGenieSdk getUserBindDeviceList : " + new Gson().toJson(result));
                if (!result.isEmpty()) {
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_USER_DEVICE_LIST).result(true).content(result).send();
                } else {
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_USER_DEVICE_LIST).result(true).content(result).send();
                    Log.d(TAG, "AliGenieSdk getUserBindDeviceList error 11111 ");
                }
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_USER_DEVICE_LIST).result(false).content("error 6" + code + " : " + message).send();
                Log.d(TAG, "AliGenieSdk getUserBindDeviceList error 222222 ");
            }
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_USER_DEVICE_LIST).result(false).content("error 7" + err.code + err.message).send();
            Log.d(TAG, "AliGenieSdk getUserBindDeviceList error 3333333 ");
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            Event.newBuilder().type(Event.MESSAGE_TYPE_GET_USER_DEVICE_LIST).result(false).content("error 8" + err.code + err.message).send();
            Log.d(TAG, "AliGenieSdk getUserBindDeviceList error 444444 ");
        }
    }

    /**
     * 解除绑定用户
     */
    public static void unbindUser() {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UnbindAligenieUserRequest request = new UnbindAligenieUserRequest()
                .setLoginStateAccessToken(INXNIConstant.ACCESS_TOKEN);
        try {
            UnbindAligenieUserResponse unbindAligenieUser = client.unbindAligenieUser(request);
            UnbindAligenieUserResponseBody userResponseBody = unbindAligenieUser.getBody();
            Integer code = userResponseBody.getCode();
            String message = userResponseBody.getMessage();
            if (MSG_RETURN_SUCCESS_CODE == code) {
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_USER).result(true).send();
            } else if ("InvalidAuthentication".equals(code.toString())) {
                //登录状态失效
                Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_USER).result(false).content("unbind error:" + code + " , " + message).send();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Event.newBuilder().type(Event.MESSAGE_TYPE_UNBIND_USER).result(false).content("unbind error:" + e.getMessage()).send();
        }

    }

    /**
     * 基站固件信息
     */
    public static void getDeviceBasicInfo(String deviceOpenId) {
        try {
            client = createClient(INXNIConstant.ALI_GENIE_ACCESS_KEY_ID, INXNIConstant.ALI_GENIE_ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        LogUtils.i("getDeviceBasicInfo INXNIConstant.ENCODETYPE : " + INXNIConstant.ENCODETYPE);
//        LogUtils.i("getDeviceBasicInfo INXNIConstant.ENCODEKEY : " + INXNIConstant.ENCODEKEY);
//        LogUtils.i("getDeviceBasicInfo OPEN_ID : " + deviceOpenId);
        GetDeviceBasicInfoRequest.GetDeviceBasicInfoRequestDeviceInfo deviceInfo = new GetDeviceBasicInfoRequest.GetDeviceBasicInfoRequestDeviceInfo()
                .setEncodeType(INXNIConstant.ENCODETYPE)
                .setEncodeKey(INXNIConstant.ENCODEKEY)
                .setIdType("OPEN_ID")
                .setId(deviceOpenId);
        GetDeviceBasicInfoRequest getDeviceBasicInfoRequest = new GetDeviceBasicInfoRequest()
                .setDeviceInfo(deviceInfo);
        try {
            GetDeviceBasicInfoResponseBody info = client.getDeviceBasicInfo(getDeviceBasicInfoRequest).getBody();
            //LogUtils.i("getDeviceBasicInfo 数据返回 : " + new Gson().toJson(info));
            Integer code = info.getCode();
            String message = info.getMessage();
            if (code == 200 && message.equals("success")) {
                GetDeviceBasicInfoResponseBody.GetDeviceBasicInfoResponseBodyResult result = info.getResult();
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_BASIC_INFO).result(true).content(result).send();
            } else {
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_BASIC_INFO).result(false).content("get device basic info error").send();
            }
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_BASIC_INFO).result(false).content("get basic info error 0 : " + err.code + " , " + err.message).send();
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                Event.newBuilder().type(Event.MESSAGE_TYPE_GET_DEVICE_BASIC_INFO).result(false).content("get basic info error 1 : " + err.code + " , " + err.message).send();
            }
        }
    }


    /**
     * Json 转成 Map<>
     *
     * @param jsonStr
     * @return
     */
    public static Map<String, Object> getMapForJson(String jsonStr) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonStr);

            Iterator<String> keyIter = jsonObject.keys();
            String key;
            Object value;
            Map<String, Object> valueMap = new HashMap<String, Object>();
            while (keyIter.hasNext()) {
                key = keyIter.next();
                value = jsonObject.get(key);
                valueMap.put(key, value);
            }
            return valueMap;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            Log.e("StringUtil", e.toString());
        }
        return null;
    }

    public interface OnCallBack {
        void sendOpenApiData();

    }

    public void setCallBack(OnCallBack callBack) {
        this.callBack = callBack;
    }

    public DeviceStatus getCurrentMusic() {
        return currentMusic;
    }

    public void setCurrentMusic(DeviceStatus currentMusic) {
        this.currentMusic = currentMusic;
    }
}
